#!/usr/bin/perl
# 
# CGI-BIN script to add a record to a database
#
# Parameters: 
#             db=DBFile
#             form=Formfile
#         all others - fields for the record
#
use Counter;
use Counter::CGI;
use CGI::Carp;
use HTML::TreeBuilder;
use FillForm;
use POSIX;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8

$entry = new Counter::CGI;

$filename = $entry->param(db);

eval '$file = FileTable::open($filename, O_RDWR)';
if ($@) {
    dieform($@);
}
#
# Special check for the places DB: Name must not exist, because creating
# a new one with the same name clobbers the old one (unique index and
# REPLACE INTO does this for you.
# Shows why this stuff is done the wrong way.
#
if ($filename eq "db/places") {
    $name = $entry->param(name);
    $existrec = $file->getbykey("name", $name);
    if ($existrec) {
	dieform("Name $name already exists");
    }
}

$record = $file->newnum();
if (!defined($record)) {
    dieform("Could not create record");
}
$file = $entry->param(form);

warn "Filling in form $file with data from $file $index\n";
# Manipulate in a few more things - to make them available at need
$record->{_key} = $record->key();
$record->{_file} = $filename;
for $param ($entry->param) {
    if ($param !~ /^(db|form)$/) {
	$record->{$param} = $entry->param($param);
    }
}
	
$record->store(); # Store the template record.
                  # Not quite nice, but....it works.

$doc = FillForm::fillform($record, $file);
	      
print <<EoF;
Content-type: text/html; charset="utf-8"

EoF

print $doc->as_HTML;



sub dieform {

    my $msg = shift;

    print <<EoF;
content-type: text/html; charset="utf-8"

<html>
<head>
<title>Error message</title>
</head>
<body>
<h1>Error</h1>
Your request could not be completed.
<p>
Reason: $msg
<p>
<!-- appropriate BACK buttons go here -->
</body>
EoF
    die "Error $msg\n";
}

